<template>
  <div class="select-company-wrapper">
    <a-popover trigger="click" :visible="clicked" @visibleChange="handleClickChange" placement="bottom">
      <div style="display: flex; align-items: center; cursor: pointer; min-height: 24px">
        <i v-if="hasLeftIcon" class="iconfont icon-gongsi-2-line2x fs16 mr8" style="color: #55565d" @click="(e) => e.preventDefault()" />
        <span class="font-title" @click="(e) => e.preventDefault()">{{ showSelect ? showSelect : site.selectName }}</span>
        <i class="iconfont icon-swap2x fs16 ml8" @click="(e) => e.preventDefault()" />
      </div>
      <div slot="content">
        <a-input-search class="mb8" style="width: 270px" placeholder="搜索关键字" :allow-clear="true" @change="onSearchChange" />
        <a-tree
          :show-icon="true"
          :tree-data="dataList"
          :replaceFields="replaceFields"
          :expanded-keys="expandedKeys"
          :blockNode="true"
          style="max-width: 300px; max-height: 400px; overflow: auto"
          @expand="onExpand"
          @select="onSelect"
        >
          <div slot="custom" slot-scope="item">
            <div style="display: flex; align-items: center">
              <a-radio v-if="item.companyList === null" :checked="site.selectId === item.id" slot="icon" />
              <div style="flex: 1">
                <span v-html="item.name"></span>
              </div>
            </div>
          </div>
        </a-tree>
      </div>
    </a-popover>
  </div>
</template>

<script>
import { findCompanyGroupReq } from "./api";
import { ruleTitle, addTreeSlot, allCompany } from "./funcs";
import { mapState } from "vuex";
import _ from "lodash";
import { findAllParentIds } from "@/utils/tools";
export default {
  props: {
    hasLeftIcon: {
      // 是否有左边图标
      type: Boolean,
      default: true
    },
    showSelect: {
      // 是否显示选中的
      type: String,
      default: undefined
    }
  },
  data() {
    return {
      // 树结构
      replaceFields: {
        children: "companyList",
        title: "name",
        key: "id",
        value: "id"
      },
      // popover显示状态
      clicked: false,
      // 树数据
      dataList: [],
      expandedKeys: []
    };
  },
  computed: {
    ...mapState(["site"]),
    selectName() {
      return this.site.selectName;
    }
  },
  created() {
    this.findCompanyGroup();
  },
  methods: {
    updateSync() {
      this.$emit("update:siteIds", this.site.selectAllIds);
      this.$emit("update:siteName", this.selectName);
      this.$emit("update:selectTreeId", this.site.selectId);
      this.$emit("update:type", this.site.selectType);
    },
    onSearchChange: _.debounce(function (event) {
      this.findCompanyGroup(event.target.value);
    }, 1000),
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
    },
    // popover显示方法
    handleClickChange(visible) {
      this.clicked = visible;
    },
    // 选择树点击事件
    onSelect(selectedKeys, info) {
      if (selectedKeys.length === 0) {
        return;
      }
      if (info.node.dataRef.type === "group" || info.node.dataRef.type === "site") {
        // 分组
        if (info.node.dataRef.companyList && info.node.dataRef.companyList.length > 0) {
          const idArr = [];
          allCompany(info.node.dataRef.companyList, idArr);
          this.$store.commit("site/updateSelected", {
            selectAllIds: idArr.join(),
            selectName: info.node.dataRef.name
          });
        } else {
          // 分组中没有任何用工单位，如果传空字符串，会返回所有。不符合预期，那么就将分组id传入，服务器会返回空数据，符合预期
          this.$store.commit("site/updateSelected", {
            selectAllIds: info.node.dataRef.id,
            selectName: info.node.dataRef.name
          });
        }
      } else if (info.node.dataRef.type === "company") {
        this.$store.commit("site/updateSelected", {
          selectAllIds: info.node.dataRef.id,
          selectName: info.node.dataRef.name
        });
      }

      // 开始替换
      let name = this.selectName.replace(new RegExp('<span style="color: #3C8AFF">', "g"), "");
      name = name.replace(new RegExp("</span>", "g"), "");

      this.$store.commit("site/updateSelected", {
        selectId: info.node.dataRef.id !== null ? info.node.dataRef.id : "-1",
        selectName: name,
        selectType: info.node.dataRef.type
      });

      // 将数据发送的父组件
      this.updateSync();
      this.clicked = false;

      if (info.node.dataRef.type === "group") {
        sessionStorage.setItem("tenantId", info.node.dataRef.id);
      } else if (info.node.dataRef.type === "site") {
        sessionStorage.setItem("tenantId", "");
      } else {
        sessionStorage.setItem("tenantId", "-1");
      }

      this.$emit("selectChange");
    },
    // 查询所有组和用工单位
    findCompanyGroup(value) {
      findCompanyGroupReq({ name: value || undefined })
        .then((res) => {
          const dataListTemp = addTreeSlot(res.data);

          dataListTemp.map((item, index) => {
            dataListTemp[index].name = ruleTitle(dataListTemp[index].name, value);
            if (item.companyList) {
              item.companyList.map((item2, index2) => {
                dataListTemp[index].companyList[index2].name = ruleTitle(dataListTemp[index].companyList[index2].name, value);
              });
            }
          });

          if (value) {
            this.expandedKeys = findAllParentIds(this.dataList);
          }
          this.dataList = dataListTemp;

          if (!this.site.selectName) {
            // 第一次进来，本地没有缓存，就默认选择site
            this.$store.commit("site/updateSelected", {
              companyTree: JSON.stringify(this.dataList),
              selectId: this.dataList[0] ? this.dataList[0].id : "-1",
              selectName: this.dataList[0] ? this.dataList[0].name : null,
              selectType: "site"
            });
            // 默认选择第一个，模拟点击操作
            var that = this;
            const info = {
              node: {
                dataRef: that.dataList[0]
              }
            };
            setTimeout(() => {
              this.onSelect([this.site.selectId], info);
            }, 0);
          } else {
            this.$store.commit("site/updateSelected", {
              companyTree: JSON.stringify(this.dataList)
            });
            this.updateSync();
          }
        })
        .catch((err) => {
          console.log("Company load error", err);
        });
    }
  }
};
</script>

<style lang="scss">
.select-company-wrapper {
  .iconfont {
    color: var(--primary);
  }
  .font-title {
    font-size: 16px;
    font-weight: 500;
    color: #55565d;
    line-height: 22px;
  }
}
</style>
